<template>
  <el-button type="success" @click="dialogVisible=true">添加+</el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="index" label="序号" width="90" />
    <el-table-column prop="userName" label="用户名" width="120" />
    <el-table-column prop="roleName" label="角色名" width="120" />
    <el-table-column prop="sex" label="性别" width="120" >
        <template #default="scope">
            <el-tag type="primary" v-if="scope.row.sex==true">男</el-tag>
            <el-tag type="danger" v-else>女</el-tag>
        </template>
    </el-table-column>
    <el-table-column prop="provinceName" label="所在省份" width="120" >
      <template #default="scope">
        {{ getProvinceName(scope.row.provinceName) }}
      </template>
    </el-table-column>
    <el-table-column prop="cityName" label="所在市" width="120" >
      <template #default="scope">
        {{ getCityName(scope.row.cityName) }}
      </template>
    </el-table-column>
    <el-table-column prop="regionName" label="所在县" width="120" >
       <template #default="scope">
        {{ getRegionName(scope.row.regionName) }}
      </template>
    </el-table-column>
    <el-table-column prop="address" label="地址详情" width="100" >
      <template #default="scope">
        <el-tooltip
        class="box-item"
        effect="dark"
        :content="scope.row.address"
        placement="top-start"
      >
        <span v-if="scope.row.address.length>5">{{ scope.row.address.substring(0,5)+'...' }}</span>
        <span v-else>{{ scope.row.address }}</span>
      </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="createUserName" label="创建人" width="120" />
    <el-table-column prop="createTime" label="创建时间" width="180" >
      <template v-slot="scope">
        {{ scope.row.createTime .substring(0,10) }}{{ scope.row.createTime .substring(11,19) }}
      </template>
    </el-table-column>
    <el-table-column prop="updateUserName" label="修改人" width="120" />
    <el-table-column prop="updateTime" label="修改时间" width="180" >
    <template v-slot="scope">
        {{ scope.row.updateTime .substring(0,10) }}{{ scope.row.updateTime .substring(11,19) }}
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleClick(scope.row.id)">
          删除
        </el-button>
        <el-button link type="primary" size="small" @click="Update(scope.row)">修改</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--添加用户-->
   <el-dialog
    v-model="dialogVisible"
    title="添加"
    width="700"

  >
   <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="ruleForm.userName" />
    </el-form-item>
       <el-form-item label="性别" prop="sex">
      <el-radio-group v-model="ruleForm.sex">
        <el-radio :value="true">男</el-radio>
        <el-radio :value="false">女</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="部门:" prop="departmentId">
              <el-select v-model="ruleForm.departmentId" placeholder="请选择">
                <el-option label="IT信息部" :value="1" />
                <el-option label="人力资源部" :value="2" />
                <el-option label="财务部" :value="3" />
                <el-option label="销售部" :value="4" />
                <el-option label="行政部" :value="5" />
                </el-select>
            </el-form-item>
     <el-form-item label="所在地址" >
      <el-select 
      v-model="ruleForm.provinceName" 
      placeholder="请选择省份" 
      @change="handleProvinceChange"
      style="width: 120px; margin-right: 8px;"
    >
      <el-option 
        v-for="item in provinceList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>

    <!-- 城市选择（依赖省份） -->
    <el-select 
      v-model="ruleForm.cityName" 
      placeholder="请选择市" 
      @change="handleCityChange"
      style="width: 120px; margin-right: 8px;"
    >
      <el-option 
        v-for="item in cityList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>

    <!-- 区县选择（依赖城市） -->
    <el-select 
      v-model="ruleForm.regionName" 
      placeholder="请选择县" 
      style="width: 120px;"
    >
      <el-option 
        v-for="item in districtList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>
    </el-form-item>
    <el-form-item label="详细地址" prop="address">
      <el-input v-model="ruleForm.address" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        添加
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
<!--修改用户-->
   <el-dialog
    v-model="UndialogVisible"
    title="修改"
    width="700"

  >
 <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="ruleForm.userName" />
    </el-form-item>
      <el-form-item label="性别" prop="sex">
      <el-radio-group v-model="ruleForm.sex">
        <el-radio :value="true">男</el-radio>
        <el-radio :value="false">女</el-radio>
      </el-radio-group>
    </el-form-item>
     <el-form-item label="部门:" prop="departmentId">
              <el-select v-model="ruleForm.departmentId" placeholder="请选择">
                <el-option label="IT信息部" :value="1" />
                <el-option label="人力资源部" :value="2" />
                <el-option label="财务部" :value="3" />
                <el-option label="销售部" :value="4" />
                <el-option label="行政部" :value="5" />
                </el-select>
            </el-form-item>
     <el-form-item label="所在地址" prop="detailed">
      <el-select 
      v-model="ruleForm.provinceName" 
      placeholder="请选择省份" 
      @change="handleProvinceChange"
      style="width: 120px; margin-right: 8px;"
    >
      <el-option 
        v-for="item in provinceList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>

    <!-- 城市选择（依赖省份） -->
    <el-select 
      v-model="ruleForm.cityName" 
      placeholder="请选择市" 
      @change="handleCityChange"
      style="width: 120px; margin-right: 8px;"
    >
      <el-option 
        v-for="item in cityList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>

    <!-- 区县选择（依赖城市） -->
    <el-select 
      v-model="ruleForm.regionName" 
      placeholder="请选择县" 
      style="width: 120px;"
    >
      <el-option 
        v-for="item in districtList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>

    </el-form-item>
    <el-form-item label="详细地址" prop="address">
      <el-input v-model="ruleForm.address" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="UpdateData">
        修改
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref ,reactive, onMounted, watch, nextTick} from 'vue'
import { ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

import { ElMessage } from 'element-plus'
import { id } from 'element-plus/es/locales.mjs'
//省市县全国
import { regionData, codeToText } from 'element-china-area-data'
import http from '../lanjieqi/lan1'
import axios from '../lanjieqi/lan'
//弹窗显隐
const dialogVisible = ref(false)
const UndialogVisible = ref(false)

const pricenter:any=ref([])
//获取省份表
const getcity=()=>
{
  axios.get("api/User/GetProviceShow").then(res=>
  {
     pricenter.value=res.data.data
  })
}
const getfdhj=(id:any)=>
{
  if(id)
  {
    get(id)
  }
  ruleForm.cityId="";
  ruleForm.detailed="";
}
const city:any=ref([])
//获取市表
const get=(id:any)=>
{
  axios.get("/api/User/GetCity",{params:{provinceId:id}}).then(res=>
  {
     city.value=res.data.data
  })
}
const getcityId=(id:any)=>
{
  if(id)
  {
    getcounty(id)
  }
  ruleForm.detailed="";
}
//获取县表
const county:any=ref([])
const getcounty=(id:any)=>
{
  axios.get("api/User/GetCounty",{params:{cityId:id}}).then(res=>
  {
     county.value=res.data.data
  })
}


//显示
const tableData = ref()
const seach=()=>
{
  axios.get("api/User/GetUserShow").then(res=>
  {
    tableData.value=res.data.data
  })
}
//生命周期函数
onMounted(()=>
{
  seach()
  getcity()
})
//修改
const Update=(row:any)=>
{
  UndialogVisible.value=true
   console.log(row);
    Object.assign(ruleForm,row);
    ruleForm.id=row.id;
    //await getcity();
    //await get(row.provinceId);
    //await getcounty(row.cityId);
    handleProvinceChange(row.provinceName);
    nextTick(()=>
    {
      ruleForm.cityName=row.cityName;
      handleCityChange(row.cityName);
      nextTick(()=>
      {
        ruleForm.regionName=row.regionName;
      })
    })
    
    
}
const UpdateData=()=>
{
  http.put("api/User/UpdateUser",ruleForm).then(res=>
  {
    if(res.data.code==200)
    {
      ElMessage.success(res.data.message)
      seach()
      UndialogVisible.value=false
    }
    else
    {
      ElMessage.error(res.data.message)
    }
  })
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id:'',
  userName: '',
  sex: true,
  detailed: '',
  address: '',
  provinceId:'',
  cityId:'',
  departmentId:'',
  cityName:'',
  regionName:'',
  provinceName:''
})
//非空判断
const rules = reactive<FormRules>({
  userName: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 2, max: 15, message: '用户名为2-15个字符', trigger: 'blur' },
  ],
  sex: [
    {
      required: true,
      message: '性别不能为空',
      trigger: 'change',
    },
  ],
  detailed: [
    {
      required: true,
      message: '不能为空',
      trigger: 'change',
    },
  ],
  address: [
    {
      required: true,
      message: '不能为空',
      trigger: 'change',
    },
  ],

})
//添加
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) 
    {
      http.post("api/User/AddUser",ruleForm).then(res=>
      {
        if(res.data.code==200)
        {
          ElMessage.success(res.data.message)
          seach()
          dialogVisible.value=false
        }
        else
        {
          ElMessage.error(res.data.message)
        }
      })
    } 
    else 
    {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//删除用户
const handleClick = (id:any) => 
{
  console.log(id);
  
   ElMessageBox.confirm(
    '请确认要删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
     http.delete("api/User/DeleteUser",{params:{id:id}}).then(res=>
     {
      if(res.data.code==200)
      {
        ElMessage.success(res.data.message)
        seach()
      }
      else
      {
        ElMessage.error(res.data.message)
        
      }
     })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}


// 省份列表
const provinceList = regionData
// 城市列表
const cityList = ref<any[]>([])
// 区县列表
const districtList = ref<any[]>([])

// 使用你指定的ID名称


// 省份改变时，加载对应城市
const handleProvinceChange = (provinceCode: string) => {
  ruleForm.cityName=''
  ruleForm.regionName=''

  
  const province = regionData.find(item => item.value === provinceCode)
  if (province && province.children) {
    cityList.value = province.children
  } else {
    cityList.value = []
  }
}

// 城市改变时，加载对应区县
const handleCityChange = (cityCode: string) => {
    ruleForm.regionName=''
  
  const province = regionData.find(item => item.value === ruleForm.provinceName)
  if (province) {
    const city = province.children?.find(item => item.value === cityCode)

    if (city?.children) {
      districtList.value = city.children
    } else {
      districtList.value = []
      console.warn('当前城市无区县数据')
    }
  }
}
console.log(regionData); 
// 监听 provinceId 变化，初始化城市列表
watch(()=>ruleForm.provinceName, (newVal) => {
  if (newVal) {
    handleProvinceChange(newVal)
  }
})

// 监听 cityId 变化，初始化区县列表
watch(()=>ruleForm.cityName, (newVal) => {
  if (newVal) {
    handleCityChange(newVal)
  }
})
// 编码转名称的工具函数
const getProvinceName = (code: string) => codeToText[code] || '--'
const getCityName = (code: string) => codeToText[code] || '--'
const getRegionName = (code: string) => codeToText[code] || '--'






</script>
<style>
.tooltip-base-box {
  width: 600px;
}
.tooltip-base-box .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tooltip-base-box .center {
  justify-content: center;
}
.tooltip-base-box .box-item {
  width: 110px;
  margin-top: 10px;
}
</style>